
<template>
  <div class="accountList">
    <div class="searchBox">
      <el-form :model="searchForm" ref="searchFormRef">
        <el-row>
          <el-form-item prop="efficacyDictId">
            <div class="item">
              <span v-html="'功效'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.efficacyDictId"
                placeholder="请选择功效"
                size="mini"
              >
                <el-option
                  v-for="item in efficacyDictOptions"
                  :key="item.v"
                  :label="item.v"
                  :value="item.k"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="crowdDictId">
            <div class="item">
              <span v-html="'使用人群'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.crowdDictId"
                placeholder="请选择使用人群"
                size="mini"
              >
                <el-option
                  v-for="item in crowdDictOptions"
                  :key="item.v"
                  :label="item.v"
                  :value="item.k"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="positionDictId">
            <div class="item">
              <span v-html="'作用部位'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.positionDictId"
                placeholder="请选择作用部位"
                size="mini"
              >
                <el-option
                  v-for="item in positionDictOptions"
                  :key="item.v"
                  :label="item.v"
                  :value="item.k"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              @click="searchClick"
              icon="el-icon-search"
              type="primary"
              size="mini"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetClick"
              >重置</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="topBtn">
      <el-button
        v-has="'efficacy:plan:add'"
        size="mini"
        @click="addEfficacyClick"
        type="success"
        plain
        icon="el-icon-plus"
        >新增方案</el-button
      >
    </div>

    <div class="tableBox" ref="tableBoxRef">
      <el-table
       :height="605"
        v-loading="tableLoading"
        :header-cell-style="{
          background: '#F8F8F8',
          color: '#333',
          fontSize: '16px',
          fontWeight: '700',
        }"
        border
        :span-method="objectSpanMethod"
        :data="demoData"
        style="width: 100%"
      >
        <el-table-column
          prop="efficacyDictId"
          align="center"
          label="功效" 
        >
        <template slot-scope="scope">
           {{efficacyDictMap[scope.row.efficacyDictId]}}
        </template>
        </el-table-column>
        <el-table-column
          prop="crowds"
          align="center"
          label="使用人群"
           
        >
         <template slot-scope="scope">
           <div v-for="(item,index) in scope.row.crowds" :key="index" style="display:inline-block">
              {{crowdDictMap[item]}};
           </div>
        </template>
        </el-table-column>
        <el-table-column
          prop="evaluateDictId"
          align="center"
          label="功效评价"
           
        >
         <template slot-scope="scope">
         
              {{judgmentMap[scope.row.evaluateDictId]}}
         
        </template>
        </el-table-column>
        <el-table-column
          prop="positions"
          align="center"
          label="作用部位"
           
        >
        <template slot-scope="scope">
           <div v-for="(item,index) in scope.row.positions" :key="index" style="display:inline-block">
              {{positionDictMap[item]}};
           </div>
        </template>
        </el-table-column>
        <el-table-column
          prop="must"
          align="center"
          label="必做"
           
        >
        </el-table-column>
        <el-table-column
          prop="choose"
          align="center"
          label="选做"
           
        >
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'efficacy:plan:edit'"
              @click="editClick(scope.row, scope.$index)"
              >编辑</el-button
            >
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="text"
              @click="delClick(scope.row)"
              v-has="'efficacy:plan:delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

       <el-card class="footer" v-if="total > 0">
         <div>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
       </el-card>
    </div>

    <!-- 新增/修改权限 -->
    <el-dialog :close-on-click-modal="false" 
      :title="title"
      :visible.sync="addEditDialogVisible"
      width="700px"
      @open="addEditDialogOpen"
      class="addEditAccountDialog"
    >
      <div class="content">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditFormRef"
        >
          <el-row>
            <el-col :span="11">
              <el-form-item prop="efficacyDictId" label="功效：">
                <div class="item">
                  <el-select filterable 
                    clearable
                    v-model="addEditForm.efficacyDictId"
                    placeholder="请选择功效"
                    size="mini"
                  >
                    <el-option
                      v-for="item in efficacyDictOptions"
                      :key="item.v"
                      :label="item.v"
                      :value="item.k"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="11" style="margin-left: 30px">
              <el-form-item prop="crowds" label="使用人群：">
                <div class="item">
                  <el-select filterable 
                    multiple
                    clearable
                    v-model="addEditForm.crowds"
                    placeholder="请选择使用人群"
                    size="mini"
                  >
                    <el-option
                      v-for="item in crowdDictOptions"
                      :key="item.v"
                      :label="item.v"
                      :value="item.k"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <div
            v-for="(item, index) in addEditForm.details"
            :key="index"
            class="content-style"
          >
            <el-row>
              <el-col :span="11">
                <el-form-item prop="evaluateDictId" label="功效评价：">
                  <div class="item">
                    <el-select filterable 
                      clearable
                      v-model="item.evaluateDictId"
                      placeholder="请选择功效评价"
                      size="mini"
                    >
                      <el-option
                        v-for="item in dictList.effect_judgment"
                        :key="item.v"
                        :label="item.v"
                        :value="item.k"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="11" style="margin-left: 30px">
                <el-form-item prop="positions" label="作用部位：">
                  <div class="item">
                    <el-select filterable 
                      multiple
                      clearable
                      v-model="item.positions"
                      placeholder="请选择作用部位"
                      size="mini"
                    >
                      <el-option
                        v-for="item in positionDictOptions"
                        :key="item.v"
                        :label="item.v"
                        :value="item.k"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item prop="must" label="必做：">
                  <div class="item">
                    <el-input
                      size="mini"
                      v-model="item.must"
                      placeholder="请输入必做"
                    ></el-input>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="11" style="margin-left: 30px">
                <el-form-item prop="choose" label="选做：">
                  <div class="item">
                    <el-input
                      size="mini"
                      v-model="item.choose"
                      placeholder="请输入选做"
                    ></el-input>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
             <el-button
             v-if='index>0'
             
              size="mini"
              type="text"
              @click="delDetail(index)"
              
              >删除</el-button
            >
          </div>
        </el-form>
      </div>
      <el-button
      style="margin-top:20px"
        size="mini"
        @click="addEfficacy"
        type="success"
        plain
        icon="el-icon-plus"
        >新增</el-button
      >
      <div class="btns">
        <el-button size="mini" @click="addEditDialogVisible = false"
          >取 消</el-button
        >
        <el-button
          v-clickForbidden
          size="mini"
          type="primary"
          @click="addEditDialogSaveClick"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      spanArr: [],
      positionDictOptions: [],
      efficacyDictOptions: [],
      crowdDictOptions: [],
      positionDictId: [],
      typeFormatter: {},
      postHead: { token: localStorage.token },
      searchForm: {
        efficacyDictId: "",
        tag: "",
        crowdDictId: "",
        positionDictId: "",
      },
      stautsOptions: [
        { label: "正常", value: 1 },
        { label: "禁用", value: 2 },
      ],
      tableLoading: false,
      tableHeight: 50,
      tableData: [],
      demoData: [],
      pageNum: 1,
      pageSize: 15,
      total: 0,
      addEditDialogVisible: false,
      addEditForm: {
        efficacyDictId: "",
        crowds: [],
        details: [
          {
            evaluateDictId: "",
            positions: [],
            must: "",
            choose: "",
          },
        ],
      },
      addEditRules: {
        efficacyDictId: [
          { required: true, message: "功效不能为空", trigger: "blur" },
        ],
        crowds: [
          { required: true, message: "使用人群不能为空", trigger: "blur" },
        ],
      },
      roleOptions: [],
      title: "新增方案",
      editId: "",
      // data: {
      //   efficacyDictId: "",
      //   crowds: [1, 2, 3],
      //   detail: [
      //     {
      //       evaluateDictId: "",
      //       dictId: [1, 2, 3],
      //       must: "",
      //       choose: "",
      //     },
      //     {
      //       evaluateDictId: "",
      //       dictId: [1, 2, 3],
      //       must: "",
      //       choose: "",
      //     },
      //     {
      //       evaluateDictId: "",
      //       dictId: [1, 2, 3],
      //       must: "",
      //       choose: "",
      //     },
      //   ],
      // },
    };
  },
  computed: {
    ...mapGetters(["dictList"]),
     efficacyDictMap() {
      let map = {}
      this.efficacyDictOptions.forEach(x => {
        map[x.k] = x.v
      })
      return map
    },
    crowdDictMap() {
      let map = {}
      this.crowdDictOptions.forEach(x => {
        map[x.k] = x.v
      })
      return map
    },
    judgmentMap() {
      let map = {}
      this.dictList.effect_judgment.forEach(x => {
        map[x.k] = x.v
      })
      return map
    },
    positionDictMap() {
      let map = {}
      this.positionDictOptions.forEach(x => {
        map[x.k] = x.v
      })
      return map
    }
  },

  created() {
    this.getEfficacyList();
  },
  methods: {
    getK(){

    },
    delDetail(index){
      this.addEditForm.details.splice(index,1)
    },
    objectSpanMethod({ row, column, rowIndex }) {
        const fields = [
          '功效',
          '使用人群',
          "操作"
         
        ]//合并的列
        var datas = this.demoData//列表数据
        var keys = 'crowds'//合并依据zhe
        if (fields.includes(column.label)) {
          const cellValue = row[keys]
          console.log(row);
          if (cellValue && fields.includes(column.label)) {
            const prevRow = datas[rowIndex - 1]
            let nextRow = datas[rowIndex + 1]
            if (prevRow && prevRow[keys] === cellValue) {
              return { rowspan: 0, colspan: 0 }
            } else {
              // return { rowspan: row.rowspan, colspan: 1 }
              let countRowspan = 1
              while (nextRow && nextRow[keys] === cellValue) {
                nextRow = datas[++countRowspan + rowIndex]
              }
              if (countRowspan > 1) {
                return { rowspan: countRowspan, colspan: 1 }
              }
            }
          }
        }
    },
    addEfficacy() {
      this.addEditForm.details.push({
        evaluateDictId: "",
        positions: [],
        must: "",
        choose: "",
      });
    },
    resetClick() {
      this.$refs.searchFormRef.resetFields();
      this.pageNum = 1;
      this.getEfficacyList();
    },
    searchClick() {
      this.pageNum = 1;
      this.getEfficacyList();
    },

    /**
     * 获取标准库列表
     * @param {*}
     */
    async getEfficacyList() {
      this.tableLoading = true;
      const res = await this.$api.efficacyList({
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        ...this.searchForm,
      });
      this.total = res.data.result.total;
      this.tableData = res.data.result.list;
       this.demoData=[]
      this.tableData.forEach((item) => {
        
        let obj = [];
        item.details.forEach((itemChild) => {
          obj = {
          
            id: item.id,
            efficacyDictId:item.efficacyDictId,
            crowds: item.crowds,
            must:itemChild.must,
            choose:itemChild.choose,
            evaluateDictId:itemChild.evaluateDictId,
            positions:itemChild.positions
          };
             this.demoData.push(obj);
        });

     
      });
      this.efficacyDictOptions = this.dictList.effect_type;
      this.crowdDictOptions = this.dictList.users;
      this.positionDictOptions = this.dictList.effective_part;
      this.tableLoading = false;
    },

    /**
     * 新增方案
     * @param {*}
     */
    addEfficacyClick() {
      this.title = "新增方案";
      this.addEditDialogVisible = true;
    },
    /**
     * 编辑按钮
     * @param {*} row
     */
    async editClick(row, index) {
      console.log(index);
      this.title = "编辑方案";
      this.addEditDialogVisible = true;
      this.editId = row.id;
        console.log(this.editId);
      this.$nextTick(() => {
        this.$api.efficacyDetail(row.id).then(res=>{
          if(res.data.code=='00000'){
           this.addEditForm=res.data.result
          }
        })
        // this.addEditForm = JSON.parse(JSON.stringify(this.tableData[index]));
        // console.log(this.addEditForm);
      });
    },
    /**
     * 删除按钮
     * @param {*} row
     */
    delClick(row) {
      this.$confirm(
        "删除后，PC和小程序端将不再显示。此操作不可恢复，确认继续删除吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$api.delEfficacy(row.id).then((res) => {
            if (res.data.code == "00000") {
              this.$message.success("删除成功");
              this.getEfficacyList();
            }
          });
        })
        .catch(() => {});
    },

    /**
     * 切换页面大小
     * @param {*} val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getEfficacyList();
    },

    /**
     * 页码切换
     * @param {*} val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.getEfficacyList();
    },

    /**
     * 打开新增和修改的回调
     * @param {*}
     */
    addEditDialogOpen() {
      this.addEditForm = {
        efficacyDictId: "",
        crowds: [],
        details: [
          {
            evaluateDictId: "",
            positions: [],
            must: "",
            choose: "",
          },
        ],
      };
    },

    /**
     * 新增编辑保存按钮
     * @param {*}
     */
    addEditDialogSaveClick() {
      this.$refs.addEditFormRef.validate(async (boolean) => {
        if (boolean) {
          console.log(this.addEditForm);
          let data = {
            id: this.editId,
            ...this.addEditForm,
          };
          if (this.title == "新增方案") {
            data.id = "";
            const res = await this.$api.addEfficacy(data);
            if (res.data.code == "00000") {
              this.$message.success("新增成功");
             this.getEfficacyList();
              this.addEditDialogVisible = false;
            }
          } else {
            const res = await this.$api.editEfficacy(data);
            if (res.data.code == "00000") {
              this.$message.success("修改成功");
              this.getEfficacyList();
              this.addEditDialogVisible = false;
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.accountList {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  .searchBox {
    .el-row {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        margin-bottom: 0;
      }
      .item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        .nameSpan {
          padding-right: 10px;
          box-sizing: border-box;
          white-space: nowrap;
        }
        .el-input {
          width: 162px;
        }
      }
    }
  }
   .topBtn {
    margin: 10px 0;
text-align: right;
  }
  .addEditAccountDialog {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
    .btns {
      text-align: right;
      margin-bottom: 0;
    }
  }
}
/deep/.el-button--success.is-plain {
  color: #fff;
  border-color: #409eff;
  background-color: #409eff;
}
/deep/.el-form-item {
  margin-bottom: 12px;
}
.content {
  height: 40vh;
  overflow-x: hidden;
  .content-style {
    background-color: #efefef;
    padding: 20px;
    margin-bottom: 10px;
  }
}
</style>